/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.database;

import java.sql.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.log4j.*;

/**
 * This bean abstracts JDBC Database access using a JNDI DataSource.
 *
 * @version 1.0
 * @author August Detlefsen for CodeMagi, Inc.
 */
public class DataSourceBean extends PreparedDataBean {
	
    // display debug output
    Logger log = Logger.getLogger(this.getClass());
	
    /**
     * Determines whether to return null or "" if a column is empty.
     * Default: false
     */
    protected boolean returnNulls = false;

    //The resource name for this bean
    protected String resourceName = "";


    /**
     * Constructor
     * 
     * @param resourceName  The JNDI resource to connect to
     */
    public DataSourceBean( String resourceName ) {
	this.resourceName = resourceName;
    }


    /**
     * Opens the database connection from the JNDI resource
     */
    protected void openConnection() throws java.sql.SQLException {

	//if an explicit connection has already been set, use that
	if (conn != null && !conn.isClosed()) return;

	try {
	    Context initCtx = new InitialContext();
	    log.debug("InitialContext: " + initCtx);

	    DataSource ds   = (DataSource)initCtx.lookup(resourceName);
	    log.debug("DataSource: " + ds.getClass().getName());
	    
	    conn = ds.getConnection();
	    log.debug("Connection: " + conn);
	} catch (javax.naming.NamingException ne) {
	    log.debug("", ne);

	    throw new SQLException("Unable to open Connection: JNDI Error");
	}
    }

}
